package edu.dlnu.gifttalk.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import edu.dlnu.gifttalk.R;
import edu.dlnu.gifttalk.entity.BaseEntity;
import edu.dlnu.gifttalk.entity.ChannelData;
import edu.dlnu.gifttalk.http.HttpManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Risky57 on 2017/6/27.
 * 首页
 */
//首页
public class HomeFragment extends Fragment {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private HomePagerAdapter mPagerAdapter;
//用来给当前fragment绑定布局，绑定的是fragment home布局
    @Nullable
    @Override
    //用来绑定布局
    public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    //初始化控件
    public void onViewCreated (View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
    }
//设置页面内容，控制网络
    @Override
    //设置页面内容，请求网络数据
    public void onActivityCreated (@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPagerAdapter = new HomePagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
        //让tablayout与viewpager联动
//        mTabLayout.setupWithViewPager(mViewPager);
        //  请求网络数据的代码，使用的是retrofit网络加载框架（具体代码在Httpmanager里）
        Call<BaseEntity<ChannelData>> channels = HttpManager.getApi().getChannels();
        channels.enqueue(new Callback<BaseEntity<ChannelData>>() {
            //请求成功，数据存储在response中
            @Override
            public void onResponse (Call<BaseEntity<ChannelData>> call, Response<BaseEntity<ChannelData>> response) {
               //网络请求成功的时候
                //请求的网络数据结果在response对象中
                //将请求的网络数据添加到适配器中
                //数据添加到适配器
                mPagerAdapter.addAll(response.body().getData().getChannels());
                mTabLayout.setupWithViewPager(mViewPager);
            }

            @Override
            public void onFailure (Call<BaseEntity<ChannelData>> call, Throwable t) {

            }
        });
    }
}